<template>
  <div class="app-container">
    <!-- 头部 -->
    <Header title="购物车"></Header>
    <Goods v-for="item in cartList" :key="item.id" :id="item.id" :state="item.goods_state" :pic="item.goods_img" 
      :title="item.goods_name" :price="item.goods_price" :count="item.goods_count" @stateChange="getNewState" >
    </Goods>
    <!-- 底部 -->
    <Footer :isFull="fullState" :amount="amt" :total="All"  @full-change="getFullState"></Footer>
  </div>
</template>

<script>
import axios from 'axios'
import Header from '@/components/Header/Header.vue'
import Goods from '@/components/Goods/Goods.vue'
import Footer from '@/components/Footer/Footer.vue'
import bus from '@/components/eventBus.js'
export default {
    components: {
        Header,
        Goods,
        Footer
    },
    data(){
        return {
        cartList: []
        }
    },
    created(){
        this.initCartList()
        //接收点击加号事件
        bus.$on('coun-add',val=>{
            this.cartList.some( item=>{
                if(item.id === val.id){
                    item.goods_count = val.value
                    return true
                }
            })
            console.log('val',val);
        })
        // 接收点击减号事件
        bus.$on('coun-sub',val=>{
            this.cartList.some( item=>{
                if(item.id === val.id){
                    item.goods_count = val.value
                    return true
                }
            })
            console.log('val',val);
        })
    },
    methods: {
        async initCartList(){
            const { data: res } = await axios.get('https://www.escook.cn/api/cart')
            if(res.status ===200){
                this.cartList = res.list
            }
            console.log(this.cartList);
        },
        getNewState(e){
            console.log(e);
            this.cartList.some( item=>{
                // 必须要根据id修改对应商品选中状态
                if(e.id === item.id){
                    item.goods_state = e.value;
                    return true;
                }
            })
        },
        getFullState(e){
            // 使用forEach过滤数组每一项，过滤的时候让每一项的选中状态都等于全选的选中状态
           this.cartList.forEach( item=> item.goods_state = e) 
        }
    },
    computed: {
        // 全选
        fullState(){
            // 这里使用every是因为只要有一项为false就返回false,定义为计算属性传递给footer组件控制全选状态正合适
           return this.cartList.every( item=>item.goods_state) 
        },
        // 合计
        amt(){
            return this.cartList.filter( item => item.goods_state).reduce( (total,item) => total += item.goods_price*item.goods_count, 0)
        },
        // 结算的全部数量
        All(){
            return this.cartList.filter( item => item.goods_state).reduce( (total,item) => total += item.goods_count, 0)
        }
    }
}
</script>

<style lang="less" >
.app-container{
  width: 100%;
  height: 100%;
  padding-bottom: 50px;
}
body{
  margin: 0;
  padding: 0;
}
</style>
